package com.dmgis.qxfw.dataservice.commonservice.service.Impl;

import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.commonservice.common.DbConfig;
import com.dmgis.qxfw.dataservice.commonservice.dmgis_pg_srv.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.commonservice.domain.UserTable;
import com.dmgis.qxfw.dataservice.commonservice.service.IUserTableService;
import com.dmgis.qxfw.dataservice.commonservice.utils.JsonUtil;
import com.dmgis.qxfw.dataservice.commonservice.utils.StringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("UserTable")
public class UserTableService implements IUserTableService {

    ProcessRequestController procon = new ProcessRequestController();

    @Override
    public boolean checkLogin(String username, String password) {
        List<UserTable> userTableList = new ArrayList<>();
        Map<String, String> selectParam = new HashMap();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(username) && !StringUtil.IsNullOrEmpty(password)) {
            strWhere.append(String.format("username='%s'", username));
            strWhere.append(String.format(" and password='%s'", password));
            selectRequest.setParam(strWhere.toString());
            try {
                selectParam.put("method", "user_table");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                //拼接sql对象
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = procon.processRequest(selectParam);
                userTableList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<UserTable>>() {
                });
            } catch (Exception e) {
                System.err.println(e.getStackTrace());
            }
            UserTable userTable = userTableList.get(0);
            if (userTableList != null && userTable !=null) {
                //验证用户是否过期
                long currentTime = System.currentTimeMillis();
                long stopTime = userTable.getStoptime().getTime();
                if (currentTime - stopTime < 0) {
                    return true;
                }
            }
        }
        return false;
    }
}
